const express = require('express');
const router = express.Router();
const utils = require('../../utils');

const filters = [
    {
        Name: '名称',
        Type: 'String',
    },
    {
        Name: '描述',
        Type: 'String',
    },
];

// technology
router.get('/',
    (req, res, next) => {
        // query
        res.locals.filter = Object.assign(
            {}, 
            res.app.modules['input-field'].generateQueryFilter(filters, req.query), 
            res.locals.filter, 
            utils.makeQueryFilters(req, 'technology'),
            { Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } }
        );

        res.locals.fields = [
            'id',
            'LastUpdateDate',
            
            '名称',
            '图片',
            '详情',
        ];
        res.locals.options = {
            sort: { 推荐指数: 'desc', 时间: 'desc', LastUpdateDate: 'desc' },
            lean: true
        };

        return next();
    },
    router.FindDocuments('technology', false, (req, res) => {
        if(!res.locals.data || !res.locals.data.total) return;

        (res.locals.data.docs || []).forEach(pol => {
            pol.详情 = utils.repalceHtmlToText(pol.详情 || '');
            pol.时间 = pol.时间 || pol.LastUpdateDate;
            delete pol.LastUpdateDate;
        });
    })
);

// technology details
router.get('/:id',
    (req, res, next) => {
        res.locals.filter = { id: req.params.id, Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } };
        res.locals.fields = [
            'id',
            'LastUpdateDate',
            '推荐指数',
            '日期',
            
            '名称',
            '图片',
            '详情',
        ];
        res.locals.options = {
            lean: true
        };

        return next();
    },
    router.FindDocuments('technology', false, (req, res) => {
        if(res.locals.data && res.locals.data.total) {
            res.locals.data = res.locals.data.docs[0];
        } else {
            res.locals.data = {};
        }
    }),
);

module.exports = router;
